const createError = require("http-errors")
const express = require("express")
const cors = require("cors")
const path = require("path")
const cookieParser = require("cookie-parser")
const logger = require("morgan")
const bodyParser = require("body-parser")

const jwt = require("jsonwebtoken")

// 压缩发送回客户端的 HTTP 响应的中间件
const compression = require("compression")
// 可以设置适当的 HTTP 标头中间件 避免一些web漏洞
const helmet = require("helmet")

const indexRouter = require("./routes/index")
const mockRouter = require("./routes/mock")

const app = express()

// 添加压缩发送回客户端的 HTTP 响应的中间件
app.use(compression()) 
// 添加设置适当的 HTTP 标头中间件
app.use(helmet())

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 设置跨域
app.use("/", cors())

app.use(logger("dev"))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())

// 设置路由路径
app.use("/index", indexRouter)
app.use("/mock",mockRouter)

// 设置静态文件路径 可以用http://localhost:3000/static/images/5.jpg 访问到public下的文件夹
let options = {
	setHeaders: function (res, path, stat) {
		res.set("Cross-Origin-Resource-Policy", "cross-origin")
	},
	// 设置强缓存
	maxAge: "3600000"
}
app.use("/static", express.static(path.join(__dirname, "public"), options))

// 返回404
app.use(function (req, res, next) {
	next(createError(404))
})

// 错误信息处理 必须在所有其它的app.use()和路由调用后才能调用
// 因此它们是需求处理过程中最后的中间件
app.use(function (err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message
	res.locals.error = req.app.get("env") === "development" ? err : {}

	// render the error page
	res.status(err.status || 500)
	res.render("error")
})

module.exports = app
